﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;

namespace ManagedUpload
{
    public class ManagedUpload : Page
    {
        private const string SEPERATOR = "\r\n";
        protected void Page_Load(object sender, EventArgs e)
        {
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            Response.Write("base dir:" + baseDir + SEPERATOR);
            //准备目录
            string dir = Request["Dictionary"];
            if (!Directory.Exists(dir))//如果路径存在，直接写入该路径
            {
                dir = Path.Combine(baseDir, dir);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
            Response.Write("dir:" + dir + SEPERATOR);
            //保存文件
            HttpPostedFile file = Request.Files[0];
            string name = file.FileName;
            int expectedLength = file.ContentLength;
            Response.Write("file:" + name + " size:" + expectedLength + SEPERATOR);
            byte[] data = ReadFromStream(file.InputStream);
            Response.Write("actual read size:" + data.Length + SEPERATOR);
            string path = Path.Combine(dir, name);
            Save(path, data);
            if (File.Exists(path))
            {
                Response.Write("remote path:" + path);
            }
        }

        private byte[] ReadFromStream(Stream stream)
        {
            byte[] data = null;
            using (MemoryStream ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                data = ms.ToArray();
                ms.Close();
            }
            return data;
        }

        private void Save(string path,byte[] data)
        {
            File.WriteAllBytes(path, data);
        }
    }
}
